package cn.sylinx.common.ext;

import cn.sylinx.common.lang.Result;
import cn.sylinx.common.lang.ResultSupport;

@SuppressWarnings("unchecked")
public final class ResultUtil {

	public static final String OK_200 = "200";

	public static Result errorResult(Object msg) {
		return errorResult("500", msg);
	}
	
	public static Result errorResult(String code, Object msg) {

		if (OK_200.equals(code)) {
			throw new RuntimeException("code:200 is not error");
		}

		Result r = new ResultSupport(false);
		r.getModels().put("code", code);
		r.getModels().put("error", msg);
		return r;
	}

	public static Result okResult(Object data) {
		Result r = new ResultSupport();
		r.setSuccess(true);
		r.getModels().put("data", data);
		return r;
	}

	public static Result okResult() {
		return okResult(null);
	}

	public static <T> T getData(Result result) {
		if (result == null) {
			return null;
		}
		return (T) result.getModels().get("data");
	}

	public static <T> T getError(Result result) {
		if (result == null) {
			return null;
		}
		return (T) result.getModels().get("error");
	}

	public static String getCode(Result result) {
		if (result == null) {
			return null;
		}
		return (String) result.getModels().get("code");
	}
}
